<template>
  <div>
    <el-form :inline="true" :model="searchForm" width="30%">
      <el-form-item label="消息内容">
        <el-input v-model="searchForm.content" placeholder="请输入消息内容"></el-input>
      </el-form-item>
      <el-form-item label="消息备注">
        <el-input v-model="searchForm.remark" placeholder="请输入消息备注"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="info" @click="refreshOaMessages">刷新</el-button>
    <el-button type="success" @click="showAddDialog">新增</el-button>
    <el-button type="danger" @click="deleteOaMessages">批量删除</el-button>
    <el-table :data="oaMessages" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="content" label="内容"></el-table-column>
      <el-table-column prop="state" label="状态"></el-table-column>
      <el-table-column prop="fromWhere" label="发件人"></el-table-column>
      <el-table-column prop="toWhere" label="收件人"></el-table-column>
      <el-table-column prop="createDate" label="创建时间"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="confirmDeleteOaMessage(scope.row.id, scope.row.name)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加消息" v-model="addVisible" width="30%"
                :close-on-click-modal="false">
      <el-form :model="addForm">
        <el-form-item label="消息内容" label-width="100px">
          <el-input v-model="addForm.content" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="消息状态" label-width="100px">
          <el-select v-model="addForm.state" placeholder="请选择状态">
            <el-option label="未读" value="未读"></el-option>
            <el-option label="已读" value="已读"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发件人" label-width="100px">
          <el-input v-model="addForm.fromWhere" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="收件人" label-width="100px">
          <el-input v-model="addForm.toWhere" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="addForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOaMessage">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="编辑消息" v-model="editVisible" width="30%"
               :close-on-click-modal="false">
      <el-form :model="editForm">
        <el-form-item label="消息内容" label-width="100px">
          <el-input v-model="editForm.content" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="消息状态" label-width="100px">
          <el-select v-model="editForm.state" placeholder="请选择状态">
            <el-option label="未读" value="未读"></el-option>
            <el-option label="已读" value="已读"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发件人" label-width="100px">
          <el-input v-model="editForm.fromWhere" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="收件人" label-width="100px">
          <el-input v-model="editForm.toWhere" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateOaMessage">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessageBox } from 'element-plus';

export default {
  name: 'OaMessageList',
  data() {
    return {
      oaMessages: [],
      searchForm: {
        content: '',
        remark: ''
      },
      addVisible: false,
      editVisible: false,
      addForm: {
        name: '',
        state: '未读',
        content: '',
        fromWhere: '',
        toWhere: '',
        remark: ''
      },
      editForm: {
        id: null,
        name: '',
        state: '',
        content: '',
        fromWhere: '',
        toWhere: '',
        remark: ''
      },
      selectedOaMessages: [] // 用于存储选中的消息
    };
  },
  methods: {
    async fetchOaMessages(params) {
      try {
        const response = await
            axios.get(`${process.env.VUE_APP_API_BASE_URL}/oaMessage/list`, {
              params });
        this.oaMessages = response.data; // 假设返回的是一个对象数组
      } catch (error) {
        console.error('Failed to fetch oaMessages:', error);
      }
    },
    onSearch() {
      const params = {
        content: this.searchForm.content,
        remark: this.searchForm.remark
      };
      this.fetchOaMessages(params);
    },
    showAddDialog() {
      this.addVisible = true;
    },
    async addOaMessage() {
      // 发送 POST 请求来添加新消息
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/oaMessage/add`, this.addForm);
        this.oaMessages.push(response.data); // 假设返回的新消息对象
        this.addVisible = false;
        this.resetAddForm();
        this.refreshOaMessages();
      } catch (error) {
        console.error('Failed to add oaMessage:', error);
      }
    },
    resetAddForm() {
      Object.keys(this.addForm).forEach(key => {
        this.addForm[key] = ''; // 将所有值设置为空字符
      });
      this.addForm.state = '未读';
    },
    showEditDialog(row) {
      this.editForm = { ...row };
      this.editVisible = true;
    },
    async updateOaMessage() {
      // 发送 PUT/PATCH 请求来更新消息
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/oaMessage/update`, this.editForm);
        const index = this.oaMessages.findIndex(oaMessage => oaMessage.id === this.editForm.id);
        if (index !== -1) {
          this.oaMessages[index] = { ...response.data }; // 假设返回更新后的消息对象
        }
        this.editVisible = false;
        this.refreshOaMessages();
      } catch (error) {
        console.error('Failed to update oaMessage:', error);
      }
    },
    confirmDeleteOaMessage(id, name) {
      ElMessageBox.confirm(
          `确定要删除消息 "${name}" 吗？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        this.deleteOaMessage(id);
      }).catch(() => {
        // 用户取消删除
      });
    },
    async deleteOaMessage(id) {
      // 发送 DELETE 请求来删除消息
      try {
        await axios.delete(`${process.env.VUE_APP_API_BASE_URL}/oaMessage/delete/${id}`);
        this.oaMessages = this.oaMessages.filter(oaMessage => oaMessage.id !== id);
        this.refreshOaMessages();
      } catch (error) {
        console.error('Failed to delete oaMessage:', error);
      }
    },
    async deleteOaMessages() {
      if (this.selectedOaMessages.length === 0) {
        this.$message({
          message: '请选择要删除的消息',
          type: 'warning'
        });
        return;
      }
      // 构建提示信息
      const names = this.selectedOaMessages.map(oaMessage => oaMessage.name).join(', ');
      const message = `确定要删除以下消息吗？\n${names}`;

      ElMessageBox.confirm(
          message,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(async () => {
        try {
          const ids = this.selectedOaMessages.map(oaMessage => oaMessage.id);
          await axios.post(`${process.env.VUE_APP_API_BASE_URL}/oaMessage/deleteByIds`, ids);
          this.oaMessages = this.oaMessages.filter(oaMessage => !ids.includes(oaMessage.id));
          this.refreshOaMessages();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        } catch (error) {
          console.error('Failed to delete oaMessages:', error);
          this.$message({
            message: '删除失败',
            type: 'error'
          });
        }
      }).catch(() => {
        // 用户取消删除
      });
    },
    handleSelectionChange(selection) {
      this.selectedOaMessages = selection;
    },
    refreshOaMessages() {
      this.fetchOaMessages();
    },
    resetForm() {
      Object.keys(this.searchForm).forEach(key => {
        this.searchForm[key] = ''; // 将所有值设置为空字符串
        // 如果字段类型不同，可以在这里添加更多的逻辑来处理不同的初始值
      });
      this.refreshOaMessages();
    }
  },
  mounted() {

    this.fetchOaMessages(); // 页面加载时立即获取消息列表
  }
};
</script>

<style scoped>
.el-select {
  width: 100%; /* 确保下拉框宽度足够 */
}
</style>